import numpy as np
import pandas as pd
from pycaret.anomaly import *

'''
对外调用接口;
提供给外部其他Python文件调用接口.
'''
def iforest_anormal_detect(data,url):
    if url:
        data1 = pd.read_excel(url)
    else:
        data1 = data
    data1.columns = ['y']
    df1 = data1.copy()
    alg = 'iforest'  # 异常值算法
    fraction = 0.009  # 异常值比例
    #创建异常值模型
    #exp = AnomalyExperiment()
    r = setup(df1.copy(), session_id = 123,verbose=False, silent=True)
    model = create_model(alg, fraction=fraction,verbose=False)
    model_results = assign_model(model,verbose=False)
    # 获取检测结果
    df2 = pd.merge(df1.reset_index(), model_results[['Anomaly']], left_index=True, right_index=True)
    label1 = np.array(df2['Anomaly']).reshape(-1, 1)
    labels = label1.tolist()
    return labels

if __name__ == "__main__":
    # 读取文件
    url = 'iForest_data.xlsx'
    data = pd.read_excel('iForest_data.xlsx')
    labels = iforest_anormal_detect(data,url)

    # 输出label,label=0为正常点，label=1为异常点
    print('lable:', labels)
